//微凌客 工具
import {router} from '@/wlkutils/router';
import platform from '@/wlkutils/platform';
/**
 * 页面跳转
 */
function toUrl(path) {
    if (!uni.$u.test.isEmpty(path)) {
        path.includes('/pages/index') ? router.replaceAll(path) : router.push(path);
    }
}

/**
 * px转rpx
 */
function pxToRpx(px) {
    let scale = uni.upx2px(100) / 100;
    return px / scale;
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
function formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"');
    return newContent;
}

//获取系统信息、判断ipX安全距离
function getTabbarHeight() {
    var systemInfo = uni.getSystemInfoSync()
    var data = {
        ...systemInfo,
        tabbarH: 50,//tabbar高度--单位px
        tabbarPaddingB: 0,//tabbar底部安全距离高度--单位px
        device: systemInfo.system.indexOf('iOS') != -1 ? 'iOS' : 'Android', //苹果或者安卓设备
    }
    let modelArr = ['10,3', '10,6', 'X', 'XR', 'XS', '11', '12', '13', '14', '15', '16'];
    let model = systemInfo.model;
    model && modelArr.forEach(item => {
        //适配iphoneX以上的底部，给tabbar一定高度的padding-bottom
        if (model.indexOf(item) != -1 && (model.indexOf('iPhone') != -1 || model.indexOf('iphone') != -1)) {
            data.tabbarH = 70
            data.tabbarPaddingB = 20
        }
    })
    return data;
}

//拨打电话
function makePhoneCall(phone) {
    uni.makePhoneCall({
        phoneNumber: phone
    });
}

// 复制
function copy(v) {
    uni.setClipboardData({
        data: v,
        success: function () {
            uni.$u.toast('复制成功');
        }
    });
}

// 保存临时图片
function saveTempFilePathImg(url, callback) {
    var scopeAlbum = 'scope.writePhotosAlbum';
    var that = this;
    if (url) {
        // #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-MP-KUAISHOU
        uni.getSetting({
            success: res => {
                if (res.authSetting[scopeAlbum]) {
                    saveNetImageToLocal(url);
                } else {
                    //向用户发起授权请求
                    uni.authorize({
                        scope: "scope.writePhotosAlbum",
                        success: () => {
                            //授权成功保存图片到系统相册
                            saveNetImageToLocal(url);
                        },
                        fail: () => {
                            uni.showModal({
                                title: '提示',
                                content: '请先在设置页面打开“保存相册”使用权限',
                                confirmText: '去设置',
                                cancelText: '算了',
                                success: data => {
                                    if (data.confirm) {
                                        uni.openSetting();
                                    }
                                }
                            });
                        },
                    });
                }
            }
        });
        // #endif
        // #ifdef H5
        uni.$u.toast('请长按图片保存')
        // #endif
    } else {
        uni.$u.toast('未找到图片')
    }
};

function saveNetImageToLocal(url) {
    uni.showLoading({
        title: '正在下载'
    });
    uni.saveImageToPhotosAlbum({
        filePath: url,
        success: () => {
            uni.hideLoading();
            uni.$u.toast('保存成功')
        },
        fail(e) {
            uni.hideLoading();
            e.errMsg != 'saveImageToPhotosAlbum:fail cancel' && tip({
                title: '下载失败，错误原因：' + e.errMsg,
                icon: "none"
            });
        }
    });
}

function tip(data) {
    setTimeout(() => {
        uni.showToast(data);
    }, 500);
}

function rgbaToRgb(rgba) {
    if (rgba.startsWith('rgba')) {     // 检查输入是否为合法的RGBA格式
        const rgbaValues = rgba.substring(rgba.indexOf('(') + 1, rgba.lastIndexOf(')')).split(',');
        const rgbValues = rgbaValues.slice(0, 3);   // 获取红色、绿色和蓝色通道的值
        return `rgb(${rgbValues.join(',')})`;   // 将三个通道的值合并为RGB颜色值
    } else {
        return rgba;   // 如果输入的不是合法的RGBA格式，直接返回原值
    }
}

function toWork(url,corpId='') {
    if(platform.get() == 'wxMiniProgram'){
        wx.openCustomerServiceChat({
            extInfo:{url:url},
            corpId:corpId,
            success(res){
                console.log(res)
            },fail(e){
                console.log(e)
            }
        })
    }else{
        location.href = url;
    }
}

function openMap(lat,lng,name, address) {
    if (lat==null||lat==''){
        uni.showToast({
            title: '暂无位置信息',
            duration: 2000,
            icon:'none'
        });
        return;
    }
    uni.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lng),
        name: name,
        address: address,
        success: function () {
        }
    });
}

function getUrlQuery(url, key) {
    const urlParts = url.split('?');
    if (urlParts.length < 2) {
        return null;
    }
    const queryString = urlParts[1];
    const queryParams = queryString.split('&');
    for (const param of queryParams) {
        const [paramKey, paramValue] = param.split('=');
        if (paramKey === key) {
            return paramValue;
        }
    }
    return null;
}

export {
    toUrl,
    pxToRpx,
    formatRichText,
    getTabbarHeight,
    makePhoneCall,
    copy,
    saveTempFilePathImg,
    rgbaToRgb,
    toWork,
    openMap,
    getUrlQuery
}